/**
 * Created by liuqingxia on 2016/4/22.
 */

$(document).ready(function () {
    clickCommitBtn();
});

/**
 * 点击"提交"按钮
 */
function clickCommitBtn() {
    $(document).on("click", "#appInsertCommit-btn", function () {
        var params = getProxyFormValues();
        if (validateParams(params)) {
            sendParamsToServer(params);
        }

    });
}

/**
 * 获取表单项值
 * @returns {{}}
 */
function getProxyFormValues() {
    var params = getFormValuesNotSkip("proxyInsert-form");
    return params;
}

/**
 * 验证用户输入的表单参数，并给予提示
 * @param params
 * @returns {boolean}
 */
function validateParams(params) {

    var pwd = "";
    var pwdAgain = "";

    for (var propName in params) {

        var value = $.trim(params[propName]);

        if (isNull(value)) {
            swal("警告", "请输入" + englishMapChinese(propName), "warning");
            return false;
        }
        if (propName == "password") {
            pwd = value;
        }
        if (propName == "passwordAgain") {
            pwdAgain = value;
        }
    }

    if (pwd != pwdAgain) {
        swal("警告", "两次输入的密码不一致，请重新输入", "warning");
        return false;
    }

    return true;
}

/**
 * 根据英文字段返回对应的中文提示
 * @param key
 * @returns {*}
 */
function englishMapChinese(key) {

    var map = {
        clusterId: "所属集群",
        name: "名称",
        host: "主机",
        serverPort: "端口",
        managerPort: "管理端口",
        user: "用户名",
        password: "密码",
        passwordAgain: "确认密码",
        status: "状态"
    };

    return map[key];

}

/**
 * 向服务端发送请求
 * @param params
 * @returns {boolean}
 */
function sendParamsToServer(params) {
    var url = getUrlBySuffix("/tddl/proxy/insert")
    try {
        $.postHttp(params, url, function (json) {
            if (json && json.success) {
                swal("成功", json['message'], "success");
                return true;
            } else {
                swal("失败", json['message'], "error");
                console.error("添加proxy失败，请查看服务器端日志");
            }
        })
    } catch (e) {
        console.log("通讯异常，请检查网络配置，异常信息为：" + e.message);
        swal("失败", e.message, "error");
    }

    return false;
}
